import React from 'react'
import Layout from '../layout/Index'
import {
  HomeOutlined,
  InfoCircleOutlined,
  FileTextOutlined,
  UnorderedListOutlined,
  PlusOutlined,
} from '@ant-design/icons'
import { Navigate, useLocation } from 'react-router-dom'
import { Local } from '../utils/storage'
const Home = React.lazy(() => import('../pages/Home'))
const About = React.lazy(() => import('../pages/About'))
const ArticleList = React.lazy(() => import('../pages/article/List'))
const ArticleAdd = React.lazy(() => import('../pages/article/Add'))
const ArticleDetail = React.lazy(() => import('../pages/article/Detail'))
const Login = React.lazy(() => import('../pages/Login'))
const NotFound = React.lazy(() => import('../pages/NotFound'))

// 路由鉴权组件：未登录跳转登录页
function RequireAuth({ children }) {
  const location = useLocation()
  const token = Local.get('token')
  if (!token) {
    return <Navigate to="/login" replace state={{ from: location }} />
  }
  return children
}
const pageRoutes = [
  {
    path: '/',
    element: (
      <RequireAuth>
        <Layout />
      </RequireAuth>
    ),
    children: [
      {
        index: true,
        title: '首页',
        key: 'home',
        icon: <HomeOutlined />,
        element: <Home />,
      },
      {
        path: '/about',
        title: '关于',
        key: 'about',
        icon: <InfoCircleOutlined />,
        element: <About />,
      },
      {
        path: '/article',
        title: '文章管理',
        key: 'article',
        icon: <FileTextOutlined />,
        children: [
          {
            path: '/article/list',
            title: '文章列表',
            key: 'articleList',
            icon: <UnorderedListOutlined />,
            element: <ArticleList />,
          },
          {
            path: '/article/add',
            title: '添加文章',
            key: 'articleAdd',
            icon: <PlusOutlined />,
            element: <ArticleAdd />,
          },
          {
            path: '/article/detail/:id',
            title: '文章详情',
            key: 'articleDetail',
            element: <ArticleDetail />,
            menuHidden: true,
            activeMenu: 'article',
          },
        ],
      },
    ],
  },
  {
    path: '/login',
    title: '登录',
    key: 'login',
    element: <Login />,
  },
  {
    path: '/404',
    title: '404',
    key: 'notFound',
    element: <NotFound />,
    menuHidden: true,
  },
  {
    path: '*',
    element: <Navigate to="/404" replace />,
  },
]

export default pageRoutes
